package com.lenovo.srl.dil.tiltbase.perfect.fragment;

import android.graphics.Point;
import android.view.View;
import android.widget.FrameLayout;

import com.lenovo.srl.dil.tiltbase.lib.fragment.BaseFragment;
import com.lenovo.srl.dil.tiltbase.lib.utils.PreferenceUtil;

public class PerfectFragment extends BaseFragment {

	public PerfectFragment() {
		this.mCtrlMode = CtrlMode.Perfect;
	}

	@Override
	protected void moveDivier(float[] sensorData) {

	}

	@Override
	protected double[] calcXYOffset(float[] sensorData, Point curBallPosition) {
		double tiltMag = Math.sqrt(sensorData[1] * sensorData[1]
				+ sensorData[2] * sensorData[2]);
		double tiltAngle = Math.asin(sensorData[2] / tiltMag) * 180 / Math.PI;
		int tiltGain = getTiltGainByTiltAngle(tiltAngle);
		double speed = tiltGain * Math.abs(tiltMag);
		double dBall = speed * (System.currentTimeMillis() - lastTimeStamp)
				/ 1000;
		FrameLayout.LayoutParams param = (FrameLayout.LayoutParams) ball
				.getLayoutParams();
		int topMargin = param.topMargin;
		int targetTopMargin = dividerLocations[mDividerIndex == -1 ? 2
				: mDividerIndex][1];
		double[] result = new double[2];

		if (moveBallX2CenterWhenUpdate()) {
			result[0] = tiltGain * Math.abs(tiltMag)
					* Math.sin(tiltAngle * Math.PI / 180);
		} else {
			result[0] = dBall * Math.sin(tiltAngle * Math.PI / 180)
					* getSpeedRatio(getInLayout(curBallPosition));
		}
		if (Math.abs(targetTopMargin - topMargin) > 30) {
			result[1] = (targetTopMargin > topMargin ? 1 : -1) * 35;
		} else {
			result[1] = 0;
		}
		return result;
	}

	float getSpeedRatio(View overIcon) {
		float ratio = PreferenceUtil.get_over_icon_speed_ratio();
		if (overIcon == null) {
			return 1;
		}
		return ratio > 1 ? 1 : ratio;
	}

	@Override
	protected boolean moveBallX2CenterWhenUpdate() {
		return PreferenceUtil.get_over_icon_speed_ratio() > 1;
	}

	@Override
	protected float getSensorDelta() {
		return .0f;
	}
}
